package com.base.cn.platform.os.service.course.cou.record;

import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.mybatis.sharding.ShardingConstant;
import com.base.cn.platform.os.common.mybatis.table.CreateTableTool;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.TT.TTServiceUtils;
import com.base.cn.platform.os.common.utils.course.MaterialType;
import com.base.cn.platform.os.common.utils.ke96.Ke96ServiceUtils;
import com.base.cn.platform.os.dao.course.cou.record.CoursePlayRecordDao;
import com.base.cn.platform.os.entity.course.catalog.CourseCatalog;
import com.base.cn.platform.os.entity.course.cou.Course;
import com.base.cn.platform.os.entity.course.cou.record.CoursePlayRecord;
import com.base.cn.platform.os.entity.course.cou.record.UserBuyCourseStudySpeed;
import com.base.cn.platform.os.entity.course.count.CouMaterialPlayNum;
import com.base.cn.platform.os.entity.course.count.CourseSubjectPlayNum;
import com.base.cn.platform.os.entity.course.count.ToLiveCount;
import com.base.cn.platform.os.entity.course.count.TopSubjectPlayCount;
import com.base.cn.platform.os.entity.course.material.CouMaterial;
import com.base.cn.platform.os.service.course.catalog.CourseCatalogBiz;
import com.base.cn.platform.os.service.course.cou.CourseBiz;
import com.base.cn.platform.os.service.course.count.CouMaterialPlayNumBiz;
import com.base.cn.platform.os.service.course.count.CourseSubjectPlayNumBiz;
import com.base.cn.platform.os.service.course.material.CouMaterialBiz;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.user.user.CusUserService;
import com.base.cn.platform.os.service.manage.user.user.SetUserDataService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.sql.DataSource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author SK
 * @since 2018-06-13
 **/
@Service
public class CoursePlayRecordBiz extends BaseBiz<CoursePlayRecord, CoursePlayRecordDao> {

    @Autowired
    private CourseBiz courseBiz;
    @Autowired
    private SetUserDataService<CoursePlayRecord> setUserDataService;
    @Autowired
    private CoursePlayRecordDao coursePlayRecordDao;
    @Autowired
    private CusUserService cusUserService;
    @Autowired
    private CourseCatalogBiz courseCatalogBiz;
    @Autowired
    private CouMaterialBiz couMaterialBiz;
    @Autowired
    private DataSource dataSource;
    @Autowired
    private CourseSubjectPlayNumBiz courseSubjectPlayNumBiz;
    @Autowired
    private CouMaterialPlayNumBiz couMaterialPlayNumBiz;
    @Autowired
    private Ke96ServiceUtils ke96ServiceUtils;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private TTServiceUtils ttServiceUtils;

    /**
     * 获取用户最后一个播放的目录节点
     *
     * @param userId 用户ID
     * @return CoursePlayRecord
     */
    public CoursePlayRecord getUserLastPlayCourseRecord(BigDecimal userId) {
        CoursePlayRecord coursePlayRecord = coursePlayRecordDao.selectUserLastPlayCourseRecord(CoursePlayRecord.class, userId);
        if (ObjectUtils.isNotEmpty(coursePlayRecord) && DataUtil.idIsNotNull(coursePlayRecord.getCatalogId())) {
            CourseCatalog courseCatalog = courseCatalogBiz.findById(coursePlayRecord.getCatalogId());
            coursePlayRecord.setCourseCatalog(courseCatalog);
            Course course = courseBiz.findById(coursePlayRecord.getBuyCourseId());
            coursePlayRecord.setBuyCourse(course);
        }
        return coursePlayRecord;
    }

    /**
     * 查询用户节点目录播放 记录
     *
     * @param userId      用户ID
     * @param buyCourseId 购买的课程ID
     * @param courseId    播放的课程ID
     * @param catalogId   目录ID
     * @return CoursePlayRecord
     */
    public CoursePlayRecord findUserCatalogPlayRecord(BigDecimal userId,
                                                      BigDecimal buyCourseId,
                                                      BigDecimal courseId,
                                                      BigDecimal catalogId) {
        return findOne(" userId = " + userId + " and buyCourseId = " + buyCourseId + " and courseId = " + courseId + " and catalogId = " + catalogId, null);
    }

    /**
     * 查询课程播放记录列表
     *
     * @param condition  课程播放记录查询条件
     * @param setCourse  设置课程
     * @param setCreator 设置前台用户
     * @return 课程播放记录列表
     */
    public List<CoursePlayRecord> findCoursePlayRecordList(CoursePlayRecord condition, boolean setCourse, boolean setCreator) {
        String where = this.where(condition);
        List<CoursePlayRecord> coursePlayRecordList = find(where, null, null);
        setUserDataService.setUserData(coursePlayRecordList, setCreator);
        this.setCoursePlayRecordCourse(coursePlayRecordList, setCourse);
        return coursePlayRecordList;
    }

    /**
     * 查询课程播放记录列表
     *
     * @param condition      课程播放记录查询条件
     * @param setCourse      设置课程
     * @param setCreator     设置前台用户
     * @param setCatalogData 设置目录数据
     * @return 课程播放记录列表
     */
    public PageInfo<CoursePlayRecord> findCoursePlayRecordPage(CoursePlayRecord condition, Pagination pagination,
                                                               boolean setCourse, boolean setCreator,
                                                               boolean setCatalogData, boolean setCatalogTeacher) {
        condition.setOrderType(1);
        String where = this.where(condition);
        PageInfo<CoursePlayRecord> pageInfo = null;
        /* try{*/
        pageInfo = findPage(where, pagination, null);
       /* }catch (Exception e){
            if(e.getMessage().contains("doesn't exist")){
                Map<String,String> tableMap = new HashMap<>();
                tableMap.put(ShardingConstant.COURSE_PLAY_RECORD_TB_NAME,condition.getUserId().toString());
                CreateTableTool.createTable(dataSource,tableMap);
                pageInfo = new PageInfo<>();
                return pageInfo;
            }
        }*/
        //设置学员用户对象
        setUserDataService.setUserData(pageInfo.getList(), setCreator);
        //设置播放记录课程
        this.setCoursePlayRecordCourse(pageInfo.getList(), setCourse);
        //设置课程目录
        this.setCoursePlayRecordCatalog(pageInfo.getList(), setCatalogData, setCatalogTeacher);
        //设置时间轴
        List<CoursePlayRecord> coursePlayRecordList = this.handlingTimeAxis(pageInfo.getList());
        //处理好时间轴后，重新设置数据
        pageInfo.setList(coursePlayRecordList);
        return pageInfo;
    }

    /**
     * 保存课程播放记录
     *
     * @param coursePlayRecord 课程播放记录
     */
    public void saveCoursePlayRecord(CoursePlayRecord coursePlayRecord) {
        boolean status = false;
        coursePlayRecord = this.createIfAbsent(coursePlayRecord).get(1);
        if (DataUtil.idIsNotNull(coursePlayRecord.getId())) {
            coursePlayRecord.setUpdateTime(new Date());
            CoursePlayRecord _record = this.createIfAbsent(coursePlayRecord).get(2);
            if (ObjectUtils.isNotEmpty(_record)) {
                if (_record.getFinish().intValue() == 1 || coursePlayRecord.getPractice() > _record.getPractice()) {
                    StringBuffer sql = new StringBuffer();
                    sql.append(" id=");
                    sql.append(coursePlayRecord.getId());
                    sql.append(" and userId=");
                    sql.append(coursePlayRecord.getUserId());
                    updateByWhereSql(coursePlayRecord, sql.toString());
                }
                if (_record.getFinish().intValue() == 1 && coursePlayRecord.getFinish() != null && coursePlayRecord.getFinish().intValue() == 2) {
                    status = true;
                }
            }
        } else {
            if (coursePlayRecord.getBuyCourseId().compareTo(new BigDecimal(-1)) == 0) {
                coursePlayRecord.setBuyCourseId(coursePlayRecord.getCourseId());
            }
            save(coursePlayRecord);
            if (coursePlayRecord.getFinish().intValue() == 2) {
                status = true;
            }
        }
        if (status) {
            cusUserService.updateUserNumberOfStatistics(coursePlayRecord.getUserId(), "studyTotalTime", coursePlayRecord.getDuration());
        }
    }

    /**
     * 专业/科目观看量 TOP 10
     *
     * @return List<TopSubjectPlayCount>
     */
    public List<TopSubjectPlayCount> queryTopSubjectPlayCount() {
        List<CourseSubjectPlayNum> courseSubjectPlayNumList = courseSubjectPlayNumBiz.find(" 1=1 order by playCount desc", 10, null);
        if (ObjectUtils.isNotEmpty(courseSubjectPlayNumList)) {
            List<TopSubjectPlayCount> subjectPlayCountList = new ArrayList<>();
            courseSubjectPlayNumList.forEach(e -> {
                TopSubjectPlayCount playCount = new TopSubjectPlayCount();
                playCount.setSubjectIds(e.getSubjectIds());
                playCount.setSubjectNum(e.getPlayCount());
                subjectPlayCountList.add(playCount);
            });
            return subjectPlayCountList;
        }
        return null;
    }

    /**
     * 访问量最高的前 10场 直播
     *
     * @return List<ToLiveCount>
     */
    public List<ToLiveCount> queryToLiveCount() {
        List<CouMaterialPlayNum> couMaterialPlayNumList = couMaterialPlayNumBiz.find(" 1=1 and typeKey='" + MaterialType.TYPE_KEY_LIVE.getKey() + "'", 10, null);
        if (ObjectUtils.isNotEmpty(couMaterialPlayNumList)) {
            String liveIds = couMaterialPlayNumList.stream().map(e -> e.getMaterialId().toString()).collect(Collectors.joining(","));
            Map<BigDecimal, CouMaterialPlayNum> couMaterialPlayNumMap = couMaterialPlayNumList.stream().collect(Collectors.toMap(e -> e.getMaterialId(), e -> e));

            Map<BigDecimal, CouMaterial> couMaterialMap = couMaterialBiz.findMaterialByIdsToMap(liveIds, false, false);
            if (ObjectUtils.isNotEmpty(couMaterialMap)) {
                List<ToLiveCount> toLiveCountList = new ArrayList<>();
                couMaterialMap.forEach((k, v) -> {
                    ToLiveCount toLiveCount = new ToLiveCount();
                    toLiveCount.setName(v.getName());
                    CouMaterialPlayNum playNum = couMaterialPlayNumMap.get(k);
                    if (playNum == null) {
                        toLiveCount.setLiveNum(0);
                    } else {
                        toLiveCount.setLiveNum(playNum.getPlayCount());
                    }
                    toLiveCountList.add(toLiveCount);
                });
                return toLiveCountList;
            }
        }
        return null;
    }

    /**
     * 查询用户学习了多少个课程
     *
     * @param userId 用户ID
     * @return 已学习的课程数据
     */
    public Integer queryUserStudyCourseNum(BigDecimal userId) {
        return coursePlayRecordDao.queryUserStudyCourseNum(CoursePlayRecord.class, userId);
    }

    /**
     * 查询用户总学习时间
     *
     * @param userId      用户ID
     * @param buyCourseId 课程ID
     * @return 学习时间
     */
    public Integer queryUserStudySumTime(BigDecimal userId, BigDecimal buyCourseId) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("buyCourseId", buyCourseId);
        return coursePlayRecordDao.queryUserStudySumTime(CoursePlayRecord.class, params);
    }

    /**
     * 查询用户课程的总学习时间列表
     *
     * @param userId       用户ID
     * @param buyCourseIds 　购买课程ID串
     * @return　List<CoursePlayRecord>
     */
    public List<CoursePlayRecord> queryUserStudySumTimeList(BigDecimal userId, String buyCourseIds) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("buyCourseIds", buyCourseIds);
        return coursePlayRecordDao.queryUserStudySumTimeList(CoursePlayRecord.class, params);
    }

    /**
     * 查询用户某一周的学习时间
     *
     * @param userId   用户ID
     * @param courseId 课程ID
     * @return 学习时间
     */
    public Integer queryUserWeekStudySumTime(BigDecimal userId, BigDecimal courseId) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("courseId", courseId);
        Map<String, String> dataMap = DateUtils.getWeekFirstLastDay(DateUtils.format(new Date(), "yyyy-MM-dd"));
        params.put("startTime", dataMap.get("firstDay"));
        params.put("endTime", dataMap.get("lastDay"));
        return coursePlayRecordDao.queryUserWeekStudySumTime(CoursePlayRecord.class, params);
    }

    /**
     * 查询用户课程的某一周的学习时间
     *
     * @param userId       用户ID
     * @param buyCourseIds 购买的课程ID
     * @return List<CoursePlayRecord>
     */
    public List<CoursePlayRecord> queryUserWeekStudySumTimeList(BigDecimal userId, String buyCourseIds) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("buyCourseIds", buyCourseIds);
        Map<String, String> dataMap = DateUtils.getWeekFirstLastDay(DateUtils.format(new Date(), "yyyy-MM-dd"));
        params.put("startTime", dataMap.get("firstDay"));
        params.put("endTime", dataMap.get("lastDay"));
        return coursePlayRecordDao.queryUserWeekStudySumTimeList(CoursePlayRecord.class, params);
    }

    /**
     * 查询用户对课程的学习的排行名次（根据学习时间进行排序）
     *
     * @param userId   用户ID
     * @param courseId 课程ID
     * @return 排名名字
     */
    public Integer queryUserStudyCourseRankings(BigDecimal userId, BigDecimal courseId) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("courseId", courseId);
        return coursePlayRecordDao.queryUserStudyCourseRankings(CoursePlayRecord.class, params);
    }

    /**
     * 查询学习时间排行第一的用户ID
     *
     * @param courseId 课程ID
     * @return 用户ID
     */
    public BigDecimal queryUserStudyCourseRankOne(BigDecimal courseId) {
        Map<String, Object> params = new HashMap<>();
        params.put("courseId", courseId);
        return coursePlayRecordDao.queryUserStudyCourseRankOne(CoursePlayRecord.class, params);
    }

    /**
     * 查询用户购买的课程的完成或未完成的节点数量
     *
     * @param params 查询条件
     * @return List<UserBuyCourseStudySpeed>
     */
    public List<UserBuyCourseStudySpeed> findUserBuyCourseStudySpeed(Map<String, String> params) {
        return coursePlayRecordDao.findUserBuyCourseStudySpeed(CoursePlayRecord.class, params);
    }
    //===============================================================================

    /**
     * 处理播放记录时间轴
     *
     * @param coursePlayRecordList 播放记录
     */
    private List<CoursePlayRecord> handlingTimeAxis(List<CoursePlayRecord> coursePlayRecordList) {
        if (ObjectUtils.isNotEmpty(coursePlayRecordList)) {
            Map<String, List<CoursePlayRecord>> coursePlayRecordListMap = coursePlayRecordList.stream().collect(Collectors.groupingBy(e -> DateUtils.format(e.getUpdateTime(), "yyyy")));
            List<CoursePlayRecord> _list = new ArrayList<>();
            coursePlayRecordListMap.forEach((k, v) -> {
                v.get(0).setTimeAxis(k);
                _list.addAll(v);
            });
            return _list;
        }
        return coursePlayRecordList;
    }

    /**
     * 验证播放记录是否存在过
     *
     * @param coursePlayRecord
     * @return
     */
    private Map<Integer, CoursePlayRecord> createIfAbsent(CoursePlayRecord coursePlayRecord) {
        CoursePlayRecord condition = new CoursePlayRecord();
        condition.setBuyCourseId(coursePlayRecord.getBuyCourseId());
        condition.setCourseId(coursePlayRecord.getCourseId());
        condition.setCatalogId(coursePlayRecord.getCatalogId());
        condition.setUserId(coursePlayRecord.getUserId());
        List<CoursePlayRecord> recordList = this.findCoursePlayRecordList(condition, false, false);
        Map<Integer, CoursePlayRecord> dataMap = new HashMap<>();
        if (ObjectUtils.isEmpty(recordList)) {
            dataMap.put(1, coursePlayRecord);
        } else {
            CoursePlayRecord database = recordList.get(0);
            try {
                dataMap.put(2, (CoursePlayRecord) BeanUtils.cloneBean(database));
            } catch (Exception e) {
                logger.error("createIfAbsent");
            }
            // 是否学完
            if (database.nonFinished()) {//未完成学习
                database.setFinish(coursePlayRecord.getFinish());
            }
            //学习时间
            Integer duration = Math.max(database.getDuration(), (coursePlayRecord.getDuration() == null ? 0 : coursePlayRecord.getDuration()));
            database.setDuration(duration);
            // 随堂练习取最大分值
            database.setPractice(Math.max(database.getPractice(), coursePlayRecord.getPractice()));
            dataMap.put(1, database);
        }
        return dataMap;
    }

    /**
     * 设置播放记录课程
     *
     * @param coursePlayRecordList 课程播放记录
     * @param setCourse            设置课程
     */
    private void setCoursePlayRecordCourse(List<CoursePlayRecord> coursePlayRecordList, boolean setCourse) {
        if (setCourse && ObjectUtils.isNotEmpty(coursePlayRecordList)) {
            Set<BigDecimal> idSet = new HashSet<>();
            coursePlayRecordList.forEach(e -> {
                if (DataUtil.idIsNotNull(e.getBuyCourseId())) {
                    idSet.add(e.getBuyCourseId());
                }
                if (DataUtil.idIsNotNull(e.getCourseId())) {
                    idSet.add(e.getCourseId());
                }
            });
            if (ObjectUtils.isNotEmpty(idSet)) {
                String courseIds = DataUtil.joining(idSet, BigDecimal::toString);
                Map<BigDecimal, Course> courseMap = courseBiz.findCourseToMapByIds(courseIds, false, false, false, false);
                coursePlayRecordList.forEach((v) -> {
                    v.setBuyCourse(courseMap.get(v.getBuyCourseId()));
                    if (v.getBuyCourseId().compareTo(v.getCourseId()) != 0) {
                        v.setCourse(courseMap.get(v.getCourseId()));
                    }
                });
            }
        }
    }

    /**
     * 设置播放记录目录数据
     *
     * @param coursePlayRecordList 播放记录列表
     * @param setCatalogData       设置目录数据
     * @param setCatalogTeacher    设置目录讲师
     */
    private void setCoursePlayRecordCatalog(List<CoursePlayRecord> coursePlayRecordList, boolean setCatalogData, boolean setCatalogTeacher) {
        if (ObjectUtils.isNotEmpty(coursePlayRecordList) && setCatalogData) {
            String catalogIds = coursePlayRecordList.stream().map(e -> e.getCatalogId().toString()).collect(Collectors.joining(","));
            Map<BigDecimal, CourseCatalog> courseCatalogMap = courseCatalogBiz.findCourseCatalogMapByIds(catalogIds, false, false, false, false);
            if (ObjectUtils.isNotEmpty(courseCatalogMap)) {
                StringJoiner joiner = new StringJoiner(",");
                courseCatalogMap.forEach((k, v) -> {
                    v.getMaterialId();
                    joiner.add(v.getMaterialId().toString());
                });
                //获取播放记录目录下的素材
                Map<BigDecimal, CouMaterial> couMaterialMap = couMaterialBiz.findMaterialByIdsToMap(joiner.toString(), false, true);
                coursePlayRecordList.forEach(e -> {
                    CourseCatalog courseCatalog = courseCatalogMap.get(e.getCatalogId());
                    if (ObjectUtils.isNotEmpty(courseCatalog)) {
                        //把目录关联的老师设置到目录中
                        CouMaterial material = couMaterialMap.get(courseCatalog.getMaterialId());
                        if (ObjectUtils.isNotEmpty(material)) {
                            courseCatalog.setTeacher(material.getTeacher());
                        }
                    }
                    e.setCourseCatalog(courseCatalog);
                });
            }
        }
    }

    /**
     * 拼接where子句
     *
     * @param condition 课程播放记录
     * @return where子句
     */
    private String where(CoursePlayRecord condition) {
        StringBuilder where = new StringBuilder(" 1 = 1");
        if (DataUtil.idIsNotNull(condition.getBuyCourseId())) {
            where.append(" and buyCourseId = ").append(condition.getBuyCourseId());
        }
        if (DataUtil.idIsNotNull(condition.getCourseId())) {
            where.append(" and courseId = ").append(condition.getCourseId());
        }
        if (DataUtil.idIsNotNull(condition.getCatalogId())) {
            where.append(" and catalogId = ").append(condition.getCatalogId());
        }
        if (DataUtil.idIsNotNull(condition.getUserId())) {
            where.append(" and userId = ").append(condition.getUserId());
        }
        if (DataUtil.isPositive(condition.getSource())) {
            where.append(" and source = ").append(condition.getSource());
        }
        if (ObjectUtils.isNotEmpty(condition.getToTime())) {
            String playDate = DateUtils.format(condition.getToTime(), "yyyy-MM-dd HH:mm");
            where.append(" and updateTime >= '" + playDate + "'");
        }
        if (ObjectUtils.isNotEmpty(condition.getEndTime())) {
            String playDate = DateUtils.format(condition.getEndTime(), "yyyy-MM-dd HH:mm");
            where.append(" and updateTime <= '" + playDate + "'");
        }
        if (ObjectUtils.isNotEmpty(condition.getCreateTime())) {
            String playDate = DateUtils.format(condition.getCreateTime(), "yyyy-MM-dd");
            where.append(" and createTime > '").append(playDate).append("'");
        }
        if (ObjectUtils.isNotEmpty(condition.getBeginUpdateTime())) {
            String updateTime = DateUtils.format(condition.getBeginUpdateTime(), "yyyy-MM-dd HH:mm");
            where.append(" and updateTime >= '").append(updateTime).append("'");
        }
        if (ObjectUtils.isNotEmpty(condition.getEndUpdateTime())) {
            String updateTime = DateUtils.format(condition.getEndUpdateTime(), "yyyy-MM-dd HH:mm");
            where.append(" and updateTime <= '").append(updateTime).append("'");
        }
        if (condition.getOrderType() == 1) {
            where.append(" order by updateTime desc");
        }
        return where.toString();
    }

    /**
     * 查询用户播放最新节点
     *
     * @param userId      用户ID
     * @param buyCourseId 购买的课程ID
     * @param courseId    播放的课程ID
     * @return CoursePlayRecord
     */
    public CoursePlayRecord findUserNewPlayRecord(BigDecimal userId,
                                                  BigDecimal buyCourseId,
                                                  BigDecimal courseId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", userId);
        params.put("courseId", courseId);
        params.put("buyCourseId", buyCourseId);
        CoursePlayRecord coursePlayRecord = coursePlayRecordDao.findUserBuyCourseStudyNew(CoursePlayRecord.class, params);
        boolean setCourse = true;
        if (ObjectUtils.isNotEmpty(coursePlayRecord) && setCourse) {
            if (coursePlayRecord.getBuyCourseId() == coursePlayRecord.getCourseId()) {
                List<CoursePlayRecord> recordList = new ArrayList<>();
                recordList.add(coursePlayRecord);
                setCoursePlayRecordCourse(recordList, setCourse);
            } else {
                coursePlayRecord.getBuyCourseId();
            }
        }
        boolean setCatalog = true;
        if (ObjectUtils.isNotEmpty(coursePlayRecord) && setCatalog) {
            CourseCatalog courseCatalog = courseCatalogBiz.findById(coursePlayRecord.getCatalogId());
            coursePlayRecord.setCourseCatalog(courseCatalog);
        }
        return coursePlayRecord;
    }


    //=====================================

    /**
     * 创建用户的学习记录表、学习明细表
     * @param userId 用户ID
     *//*
    @Async
    public void createUserPlayRecordTable(BigDecimal userId){
        Map<String,String> tableData = new HashMap<>();
        tableData.put(ShardingConstant.COURSE_LEARN_FLOW_TB_NAME,userId.toString());
        tableData.put(ShardingConstant.COURSE_PLAY_RECORD_TB_NAME,userId.toString());
        CreateTableTool.createTable(dataSource,tableData);
    }*/
    /**
     * 单课程统计 学习总人数，完成总人数，完课率（时间范围：从课程创建到昨天）
     */
    public Map<String,Object> findCourseStatis(BigDecimal buyCourseId) {
        Course course = courseBiz.findById(buyCourseId);
        long count = 0;
        long finishCount = 0;
        double finishRate = 0;
        LocalDate localDate = LocalDate.now();
        LocalDate yesterday = localDate.plusDays(-1);
        String format = yesterday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        List<CoursePlayRecord> coursePlayRecordList = this.find("buyCourseId=" + buyCourseId + " and  DATE_FORMAT(createTime, '%Y-%m-%d') <  '" + format + "'", null, null);
        if (ObjectUtils.isNotEmpty(coursePlayRecordList)) {
            count = coursePlayRecordList.stream().map(e -> e.getUserId()).distinct().count();
            List<BigDecimal> userIdList = coursePlayRecordList.stream().map(e -> e.getUserId()).distinct().collect(Collectors.toList());
            Map<BigDecimal, List<CoursePlayRecord>> coursePlayRecordLisMap = coursePlayRecordList.stream().collect(Collectors.groupingBy(e -> e.getUserId()));
            if (count != 0) {
                List<BigDecimal> finishCountList = new ArrayList<>();
                userIdList.stream().forEach(e->{
                    List<CoursePlayRecord> coursePlayRecordListTemp = coursePlayRecordLisMap.get(e);
                    long totalDuration = coursePlayRecordListTemp.stream().mapToLong(i -> i.getMaxDuration()).sum(); // 总学习时长
                    if (ObjectUtils.isNotEmpty(course.getTotleTimes()) &&course.getTotleTimes() != 0 &&  totalDuration >= course.getTotleTimes()) {
                        finishCountList.add(e);
                    }

                });
                finishCount = finishCountList.size();
                finishRate = finishCount / count;
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("count", count);
        result.put("finishCount", finishCount);
        result.put("finishRate", finishRate);
        return result;
    }



    /**
     * 课程学习走势图统计数据
     * @param courseId  课程id
     * @param timeSql 时间sql
     * @return
     */
    public Map<String,Object> findCoursePlayRecordByDate(BigDecimal courseId,List<Date> xAxisList,String timeSql) {
        StringBuilder whereSql = new StringBuilder();
        List<String> dateList = xAxisList.stream().map(e->DateUtils.format(e,"yyyy-MM-dd")).collect(Collectors.toList()); // x轴 时间
        List<Long> studyNumList = new ArrayList<>(); // y1轴 学习人数
        List<Long> studyDurationList = new ArrayList<>();// y2轴 学习时长

        whereSql.append("buyCourseId=" + courseId + " and DATE_FORMAT(createTime, '%Y-%m-%d') IN "+ timeSql);
        List<CoursePlayRecord> coursePlayRecordList = this.find(whereSql.toString(), null, null);
        if (ObjectUtils.isNotEmpty(coursePlayRecordList)) {
            Map<String, List<CoursePlayRecord>> coursePlayRecordListMap = coursePlayRecordList.stream().collect(Collectors.groupingBy(e -> DateUtils.format(e.getCreateTime(), "yyyy-MM-dd")));
            dateList.stream().forEach(e->{
                List<CoursePlayRecord> temp = coursePlayRecordListMap.get(e);
                if (ObjectUtils.isNotEmpty(temp)) {
                    long count = temp.parallelStream().map(i -> i.getUserId()).distinct().count();
                    studyNumList.add(count);
                    long studyDuration = temp.stream().mapToLong(i -> i.getMaxDuration()).sum();
                    studyDurationList.add(studyDuration);
                }else{
                    studyNumList.add(0L);
                    studyDurationList.add(0L);
                }
            });
        }else{
            dateList.stream().forEach(e->{
                studyNumList.add(0L);
                studyDurationList.add(0L);
            });
        }
        Map<String, Object> result = new HashMap<>();
        result.put("dateList", dateList);
        result.put("studyNumList", studyNumList);
        result.put("studyDurationList", studyDurationList);
        return result;

    }

    /**
     * 课程完成率走势图
     * @param courseId
     * @param xAxisList
     * @param timeSql
     * @return
     */
    public Map<String, Object> queryCourseFinishStatis(BigDecimal courseId, List<Date> xAxisList, String timeSql) {
        StringBuilder whereSql = new StringBuilder();
        List<String> dateList = xAxisList.stream().map(e->DateUtils.format(e,"yyyy-MM-dd")).collect(Collectors.toList()); // x轴 时间
        List<Integer> finishCourseNumList = new ArrayList<>(); // y1轴 完成人数
        List<Double> finishCourseRateList = new ArrayList<>();// y2轴 完成率
        Course course = courseBiz.findById(courseId);
        whereSql.append("buyCourseId=" + courseId + " AND DATE_FORMAT(createTime, '%Y-%m-%d') <= '" + dateList.get(dateList.size() - 1) + "'");
        List<CoursePlayRecord> coursePlayRecordList = this.find(whereSql.toString(), null, null);

        Map<String, List<CoursePlayRecord>> coursePlayRecordMapByDate = new HashMap<>();
        if (ObjectUtils.isNotEmpty(coursePlayRecordList)) {
            dateList.stream().forEach(e->{
                List<CoursePlayRecord> tempList = new ArrayList<>();
                coursePlayRecordList.stream().forEach(i->{
                    LocalDate thisDay = LocalDate.parse(e);
                    LocalDate courseDay = LocalDate.parse(DateUtils.format(i.getCreateTime(), "yyyy-MM-dd"));
                    if (courseDay.getDayOfYear() <= thisDay.getDayOfYear()) {
                        tempList.add(i);
                    }
                });
                coursePlayRecordMapByDate.put(e, tempList);
            });
        }
        dateList.stream().forEach(e->{
            List<CoursePlayRecord> tempCoursePlayRecordList = coursePlayRecordMapByDate.get(e);
            List<BigDecimal> finishCountList = new ArrayList<>();
            if (ObjectUtils.isNotEmpty(tempCoursePlayRecordList)) {
                //当前日期 按学员分组，求每个学员的学习时长，对比课程总时长，计算完成人数，计算完成率
                List<BigDecimal> userIdList = tempCoursePlayRecordList.stream().map(i -> i.getUserId()).distinct().collect(Collectors.toList());
                Map<BigDecimal, List<CoursePlayRecord>> tempCoursePlayRecordMapByUserId = tempCoursePlayRecordList.stream().collect(Collectors.groupingBy(i -> i.getUserId()));
                userIdList.stream().forEach(i->{
                    List<CoursePlayRecord> tempUserCoursePlayRecordList = tempCoursePlayRecordMapByUserId.get(i);
                    if (ObjectUtils.isNotEmpty(tempUserCoursePlayRecordList)) {
                        long userDuration = tempUserCoursePlayRecordList.stream().mapToLong(j -> j.getMaxDuration()).sum();
                        if (ObjectUtils.isNotEmpty(course.getTotleTimes()) &&course.getTotleTimes() != 0 &&  userDuration >= course.getTotleTimes()) {
                            finishCountList.add(i);
                        }
                    }
                });
                finishCourseNumList.add(finishCountList.size());
                finishCourseRateList.add((finishCountList.size() / userIdList.size())*100.0);
            }else{
                finishCourseNumList.add(0);
                finishCourseRateList.add(0.0);
            }
        });

        Map<String, Object> result = new HashMap<>();
        result.put("dateList", dateList);
        result.put("finishCourseNumList", finishCourseNumList);
        result.put("finishCourseRateList", finishCourseRateList);
        return result;
    }


    /**
     *
     * @param courseId 课程id
     * @param materialId 素材id
     * @param catalogId 目录id
     * @return
     */
    public Map<String, Object> liveCourseStatis(BigDecimal courseId,BigDecimal materialId,BigDecimal catalogId) {
        LocalDate localDate = LocalDate.now();
        LocalDate yesterday = localDate.plusDays(-1);
        String format = yesterday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        StringBuilder whereSql = new StringBuilder("buyCourseId=" + courseId + " and  DATE_FORMAT(createTime, '%Y-%m-%d') <  '" + format + "'");
        if (ObjectUtils.isNotEmpty(catalogId)) {
            whereSql.append(" and catalogId=" + catalogId);
        }
        List<CoursePlayRecord> coursePlayRecordList = this.find(whereSql.toString(), null, null);
        Map<String, Object> result = new HashMap<>();
        long count=0;
        long totalStudy=0;
        long average=0;
        long pcStudyCount=0;
        long mobileStudyCount=0;
        if (ObjectUtils.isNotEmpty(coursePlayRecordList)) {
            count = coursePlayRecordList.stream().map(e -> e.getUserId()).distinct().count(); // 总学习人数
            totalStudy = coursePlayRecordList.stream().mapToLong(e -> e.getMaxDuration()).sum()/60; // 总学习时长
            if (count!=0) {
                average = totalStudy / count;    // 人均学习时长（分钟）
            }
            pcStudyCount = coursePlayRecordList.stream().filter(e -> e.getSource() == 1).map(e -> e.getUser()).distinct().count();// pc 学习人数
            mobileStudyCount = coursePlayRecordList.stream().filter(e -> e.getSource() != 1).map(e -> e.getUser()).distinct().count();// mobile 学习人数
        }
        result.put("count",count);
        result.put("totalStudy", totalStudy);
        result.put("average", average);
        result.put("pcStudyCount", pcStudyCount);
        result.put("mobileStudyCount", mobileStudyCount);

        List<CouMaterial> materialByIds = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(materialId)) {
            materialByIds=couMaterialBiz.findMaterialByIds( materialId.toString(), false, false);
        }else{
            List<CourseCatalog> courseCatalogByCourseId = courseCatalogBiz.findCourseCatalogByCourseId( courseId, false, false, false, false);
            String materialIds = courseCatalogByCourseId.parallelStream()
                    .filter(m -> ObjectUtils.isNotEmpty(m.getMaterialTypeKey()) && "LIVE".equals(m.getMaterialTypeKey()))
                    .map(m -> m.getMaterialId().toString())
                    .collect(Collectors.joining(","));
            materialByIds=couMaterialBiz.findMaterialByIds( materialIds.toString(), false, false);

        }
        List<Long> onlineUserCountList = new ArrayList<>();
        List<Long> userMsgCountList = new ArrayList<>();
        List<Long> userTotalDuration = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        materialByIds.stream().forEach(e->{
            if("CC".equals(e.getPlayType())){
                List<Map> liveList = ke96ServiceUtils.getLiveList(e.getRoomId(), null, null, null, null);
                if (ObjectUtils.isNotEmpty(liveList)){
                    liveList.forEach(m -> {
                        Date startTime=null;
                        Date endTime=null;
                        String liveId= (String) m.get("id");
                        try {
                            startTime = sdf.parse(m.get("startTime").toString());
                            endTime = sdf.parse(m.get("endTime").toString());
                        } catch (ParseException parseException) {
                            parseException.printStackTrace();
                        }
                        Long minByDiff = Long.valueOf(String.valueOf(DateUtils.getMinByDiff(startTime, endTime)));
                        userTotalDuration.add(minByDiff);
                        Long liveUserView = ke96ServiceUtils.findLiveUserView(liveId);
                        Long liveUserMsg = ke96ServiceUtils.findLiveUserMsg(e.getRoomId(), liveId);
                        if (ObjectUtils.isNotEmpty(liveUserView)) {
                            onlineUserCountList.add(liveUserView);
                            userMsgCountList.add(liveUserMsg==null?0:liveUserMsg);
                        }
                    });
                }
            }else{
                Map<String, Object> liveInfoMap = ttServiceUtils.getLiveInfo(e.getRoomId());
                if ((boolean) liveInfoMap.get("success")) {
                    Map entityMap = (Map) liveInfoMap.get("entity");
                    userTotalDuration.add(Long.valueOf(entityMap.get("studentOnlineTimeTotal").toString()));
                    onlineUserCountList.add(Long.valueOf(entityMap.get("uv").toString()));
                    userMsgCountList.add(Long.valueOf(entityMap.get("chatMsgTotal").toString()));
                }else{
                    userTotalDuration.add(0L);
                    onlineUserCountList.add(0L);
                    userMsgCountList.add(0L);
                }
            }
        });
        Long totalOnlineUser = onlineUserCountList.stream().mapToLong(e -> e).sum();
        Long userMsgCount= userMsgCountList.stream().mapToLong(e -> e).sum();
        long sum = userTotalDuration.stream().mapToLong(e -> e).sum();
        long averageDuration=0;
        if (count != 0) {
            averageDuration=sum/count;
        }
        result.put("totalOnlineUser", totalOnlineUser);
        result.put("userMsgCount", userMsgCount);
        result.put("averageDuration", averageDuration);
        return result;
    }


    /**
     * 直播互动记录
     * @param materialId 素材id
     * @param pageSize 页容量
     * @param pageNum 页码
     * @return
     */
    public PageInfo<Map<String,Object>> getInteractiveByCCPage(BigDecimal materialId,Integer pageSize,Integer pageNum) {
        CouMaterial couMaterial = couMaterialBiz.findById(materialId, Collections.singletonList("roomId"));
        List<Map> liveList = ke96ServiceUtils.getLiveList(couMaterial.getRoomId(), null, null, null, null);
        List<Map<String, Object>> liveInteractiveList = new ArrayList<>();
        PageInfo<Map<String,Object>> pageInfo = new PageInfo<>();
        if (ObjectUtils.isNotEmpty(liveList)) {
            Map<String,Object> map = liveList.get(0);
            Map result= ke96ServiceUtils.getLiveInteractiveList(map.get("id").toString(),pageSize.toString(), pageNum.toString());
            if (ObjectUtils.isNotEmpty(result)) {
                liveInteractiveList= (List<Map<String, Object>>) result.get("liveViewerStatisConclusions");
                pageInfo.setList(liveInteractiveList);
                pageInfo.setPageSize(pageSize);
                pageInfo.setPageNum(pageNum);
                pageInfo.setPrePage(pageNum-1);
                pageInfo.setNextPage(pageNum+1);
                String count=result.get("count").toString();
                long pageCount = new Double(Double.parseDouble(count)).longValue();
                pageInfo.setTotal(pageCount);
                int pages= (int) (pageCount/pageSize);
                pages=pageCount%pageSize>0?pages+1:pages;
                pageInfo.setPages(pages);

            }

        }
        return pageInfo;
    }

    /**
     * 直播互动记录
     * @param materialId 素材id
     * @param pageSize 页容量
     * @param pageNum 页码
     * @return
     */
    public PageInfo<Map<String, Object>> getInteractiveByTTPage(BigDecimal materialId, Integer pageSize, Integer pageNum) {
        CouMaterial couMaterial = couMaterialBiz.findById(materialId, Collections.singletonList("roomId"));
        Map<String, Object> roomInteractiveMap = ttServiceUtils.getRoomInteractive(couMaterial.getRoomId(), pageNum, pageSize);
        List<Map<String, Object>> liveInteractiveList = new ArrayList<>();
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>();
        if ((boolean) roomInteractiveMap.get("success")) {
            Map entityMap = (Map) roomInteractiveMap.get("entity");
            liveInteractiveList = (List<Map<String, Object>>) entityMap.get("list");
            pageInfo.setList(liveInteractiveList);
            pageInfo.setPageSize(pageSize);
            pageInfo.setPageNum(pageNum);
            pageInfo.setPrePage(pageNum - 1);
            pageInfo.setNextPage(pageNum + 1);
            String count = entityMap.get("total").toString();
            long pageCount = new Double(Double.parseDouble(count)).longValue();
            pageInfo.setTotal(pageCount);
            int pages = (int) (pageCount / pageSize);
            pages = pageCount % pageSize > 0 ? pages + 1 : pages;
            pageInfo.setPages(pages);
        }
        return pageInfo;
    }


    /**
     * 获取直播聊天信息
     * @param materialId
     * @param pageSize
     * @param pageNum
     * @return
     */
    public PageInfo<Map<String, Object>> getChatMsgByCCPage(BigDecimal materialId,Integer pageSize,Integer pageNum) {
        CouMaterial couMaterial = couMaterialBiz.findById(materialId, Collections.singletonList("roomId"));
        List<Map> liveList = ke96ServiceUtils.getLiveList(couMaterial.getRoomId(), null, null, null, null);
        List<Map<String, Object>> chatMsgList = new ArrayList<>();
        PageInfo<Map<String,Object>> pageInfo = new PageInfo<>();
        if (ObjectUtils.isNotEmpty(liveList)) {
            Map<String,Object> map = liveList.get(0);
            Map result = ke96ServiceUtils.getChatMsg(map.get("id").toString(), pageSize.toString(), pageNum.toString(), couMaterial.getRoomId());
            if (ObjectUtils.isNotEmpty(result)) {
                chatMsgList= (List<Map<String, Object>>) result.get("chatMsgs");
                pageInfo.setList(chatMsgList);
                pageInfo.setPageSize(pageSize);
                pageInfo.setPageNum(pageNum);
                pageInfo.setPrePage(pageNum-1);
                pageInfo.setNextPage(pageNum+1);
                String count=result.get("count").toString();
                long pageCount = new Double(Double.parseDouble(count)).longValue();
                pageInfo.setTotal(pageCount);
                int pages= (int) (pageCount/pageSize);
                pages=pageCount%pageSize>0?pages+1:pages;
                pageInfo.setPages(pages);

            }

        }
        return pageInfo;
    }


    /**
     * 获取签到信息列表
     * @param materialId
     * @param pageSize
     * @param pageNum
     * @return
     */
    public PageInfo<Map<String, Object>> getRollCallByCCPage(BigDecimal materialId,Integer pageSize,Integer pageNum) {
        CouMaterial couMaterial = couMaterialBiz.findById(materialId, Collections.singletonList("roomId"));
        List<Map> liveList = ke96ServiceUtils.getLiveList(couMaterial.getRoomId(), null, null, null, null);
        List<Map<String, Object>> rollcallList = new ArrayList<>();
        PageInfo<Map<String,Object>> pageInfo = new PageInfo<>();
        if (ObjectUtils.isNotEmpty(liveList)) {
            Map<String,Object> map = liveList.get(0);
            Map result = ke96ServiceUtils.getUseRollCallList(map.get("id").toString(),couMaterial.getRoomId(), pageSize.toString(), pageNum.toString());
            if (ObjectUtils.isNotEmpty(result)) {
                rollcallList= (List<Map<String, Object>>) result.get("viewers");
                pageInfo.setList(rollcallList);
                pageInfo.setPageSize(pageSize);
                pageInfo.setPageNum(pageNum);
                pageInfo.setPrePage(pageNum-1);
                pageInfo.setNextPage(pageNum+1);
                String count=result.get("count").toString();
                long pageCount = new Double(Double.parseDouble(count)).longValue();
                pageInfo.setTotal(pageCount);
                int pages= (int) (pageCount/pageSize);
                pages=pageCount%pageSize>0?pages+1:pages;
                pageInfo.setPages(pages);
            }
        }
        return pageInfo;
    }

    /**
     * 获取直播聊天信息
     * @param materialId
     * @param pageSize
     * @param pageNum
     * @return
     */
    public PageInfo<Map<String, Object>> getChatMsgByTTPage(BigDecimal materialId, Integer pageSize, Integer pageNum) {
        CouMaterial couMaterial = couMaterialBiz.findById(materialId, Collections.singletonList("roomId"));
        Map<String, Object> chatRecordMap = ttServiceUtils.getChatRecord(couMaterial.getRoomId(), pageNum, pageSize);
        List<Map<String, Object>> chatMsgList = new ArrayList<>();
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>();
        if ((boolean) chatRecordMap.get("success")) {
            Map entityMap = (Map) chatRecordMap.get("entity");
            chatMsgList = (List<Map<String, Object>>) entityMap.get("list");
            pageInfo.setList(chatMsgList);
            pageInfo.setPageSize(pageSize);
            pageInfo.setPageNum(pageNum);
            pageInfo.setPrePage(pageNum - 1);
            pageInfo.setNextPage(pageNum + 1);
            String count = entityMap.get("total").toString();
            long pageCount = new Double(Double.parseDouble(count)).longValue();
            pageInfo.setTotal(pageCount);
            int pages = (int) (pageCount / pageSize);
            pages = pageCount % pageSize > 0 ? pages + 1 : pages;
            pageInfo.setPages(pages);
        }
        return pageInfo;
    }


    /**
     * 获取签到信息列表
     * @param materialId
     * @param pageSize
     * @param pageNum
     * @return
     */
    public PageInfo<Map<String, Object>> getRollCallByTTPage(BigDecimal materialId,Integer pageSize,Integer pageNum) {
        CouMaterial couMaterial = couMaterialBiz.findById(materialId, Collections.singletonList("roomId"));
        Map<String, Object> roomInteractiveMap = ttServiceUtils.getRoomInteractive(couMaterial.getRoomId(), pageNum, pageSize);
        List<Map<String, Object>> rollcallList = new ArrayList<>();
        PageInfo<Map<String,Object>> pageInfo = new PageInfo<>();
        if ((boolean) roomInteractiveMap.get("success")) {
            Map entityMap = (Map) roomInteractiveMap.get("entity");
            rollcallList = (List<Map<String, Object>>) entityMap.get("list");
            pageInfo.setList(rollcallList);
            pageInfo.setPageSize(pageSize);
            pageInfo.setPageNum(pageNum);
            pageInfo.setPrePage(pageNum - 1);
            pageInfo.setNextPage(pageNum + 1);
            String count = entityMap.get("total").toString();
            long pageCount = new Double(Double.parseDouble(count)).longValue();
            pageInfo.setTotal(pageCount);
            int pages = (int) (pageCount / pageSize);
            pages = pageCount % pageSize > 0 ? pages + 1 : pages;
            pageInfo.setPages(pages);
        }
        return pageInfo;
    }



    /**
     * 课程学习走势图统计数据
     * @param courseId  课程id
     * @param timeSql 时间sql
     * @return
     */
    public Map<String,Object> findLiveOnlineByDate(BigDecimal courseId,List<Date> xAxisList,String timeSql) {
        StringBuilder whereSql = new StringBuilder();
        List<String> dateList = xAxisList.stream().map(e->DateUtils.format(e,"yyyy-MM-dd")).collect(Collectors.toList()); // x轴 时间
        List<Long> onlineNum = new ArrayList<>(); // y轴 在线人数
        whereSql.append("courseId=" + courseId + " and materialId!=0 and DATE_FORMAT(createTime, '%Y-%m-%d') IN "+ timeSql);
        List<CourseCatalog> tempCourseCatalogList = courseCatalogBiz.find(whereSql.toString(), null, null);
        List<CourseCatalog> courseCatalogList = courseCatalogBiz.setMaterialData( tempCourseCatalogList, true);
        Map<String, List<CourseCatalog>> courseCatalogMap = courseCatalogList.stream().collect(Collectors.groupingBy(e -> DateUtils.format(e.getCreateTime(), "yyyy-MM-dd")));
        dateList.stream().forEach(e->{
            List<CourseCatalog> courseCatalogs = courseCatalogMap.get(e);
            if (ObjectUtils.isNotEmpty(courseCatalogs)) {
                List<Long> todayUa = new ArrayList<>();
                courseCatalogs.stream().forEach(i->{
                    CouMaterial material = i.getMaterial();
                    if("CC".equals(material.getPlayType())){
                        List<Map> liveList = ke96ServiceUtils.getLiveList(material.getRoomId(), null, null, null, null);
                        if (ObjectUtils.isNotEmpty(liveList)) {
                            Long onlineCount=ke96ServiceUtils.findLiveUserView(liveList.get(0).get("id").toString());
                            todayUa.add(onlineCount == null ? 0L : onlineCount);
                        }
                    }else{
                        Map<String, Object> liveInfoMap = ttServiceUtils.getLiveInfo(material.getRoomId());
                        if ((boolean) liveInfoMap.get("success")&& ObjectUtils.isNotEmpty(liveInfoMap.get("entity"))) {
                            Map entityMap = (Map) liveInfoMap.get("entity");
                            todayUa.add(Long.valueOf(entityMap.get("uv").toString()));
                        } else {
                            onlineNum.add(0L);
                        }
                    }
                });
                onlineNum.add(todayUa.stream().mapToLong(i -> i).sum());
            }else{
                onlineNum.add(0L);
            }
        });
        Map<String, Object> result = new HashMap<>();
        result.put("dateList", dateList);
        result.put("onlineUserList", onlineNum);
        return result;
    }
}
